package city.spring.modules.medicine.service.impl;

import city.spring.modules.medicine.entity.MedicineInventoryEntity;
import city.spring.modules.medicine.repository.MedicineinventoryRepository;
import city.spring.modules.medicine.service.MedicineInventoryService;
import city.spring.modules.medicine.service.MedicineService;
import city.spring.modules.system.entity.UserEntity;
import city.spring.modules.system.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.NonNull;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.security.Principal;
import java.util.List;

/**
 * Service：药品库存盘点计划表
 *
 * @author 谢金婷
 * @date 2020-07-12 22:36:56
 */
@CacheConfig(cacheNames = {MedicineinventoryServiceImpl.CACHE_NAME})
@Transactional(rollbackFor = Throwable.class)
@Service
public class MedicineinventoryServiceImpl extends ServiceImpl<MedicineinventoryRepository, MedicineInventoryEntity> implements MedicineInventoryService {

    private final MedicineService medicineService;
    private final UserService userService;
    private final MedicineinventoryRepository medicineinventoryRepository;

    public MedicineinventoryServiceImpl(MedicineService medicineService, UserService userService, MedicineinventoryRepository medicineinventoryRepository) {
        this.medicineService = medicineService;
        this.userService = userService;
        this.medicineinventoryRepository = medicineinventoryRepository;
    }

    @Override
    public void saveMedicineinventory(MedicineInventoryEntity entity, @NonNull Principal user) {

        //设置盘点人员为当前登录用户
        UserEntity userEntity = userService.getUserByIdOrAccount(user.getName());
//        System.out.println(userEntity);
//        System.out.println(userEntity.getId());
        entity.setFounder(userEntity.getId());

        entity.setIsInventory(1);

        if (!save(entity)) {
            throw new RuntimeException("保存信息失败");
        }
    }

    @Override
    public void updateMedicineinventory(MedicineInventoryEntity entity) {
        // 使用 updateById(entity); 修改数据时，将会修改 entity 对象中所有非null数据，如果某个字段为null，将会忽略该字段的修改

        boolean update = updateById(entity);
        if (!update) {
            throw new RuntimeException("修改信息失败");
        }
    }

    @Override
    public void deleteMedicineinventory(String primaryKey) {
        removeById(primaryKey);
    }

    @Override
    public void deleteMedicineinventory(List<String> primaryKeys) {
        removeByIds(primaryKeys);
    }

    @Override
    public MedicineInventoryEntity getById(String id) {
        return medicineinventoryRepository.getById(id);
    }
}